package org.dromara.common.encrypt.core.encryptor

import org.dromara.common.core.utils.StringUtils
import org.dromara.common.encrypt.core.EncryptContext
import org.dromara.common.encrypt.enumd.AlgorithmType
import org.dromara.common.encrypt.enumd.EncodeType
import org.dromara.common.encrypt.utils.EncryptUtils.decryptByRsa
import org.dromara.common.encrypt.utils.EncryptUtils.encryptByRsa
import org.dromara.common.encrypt.utils.EncryptUtils.encryptByRsaHex

/**
 * RSA算法实现
 *
 * @author 老马
 * @version 4.6.0
 * @updater LikeYouDo
 * @date 2025/1/9 10:12
 */
open class RsaEncryptor(
    private val context: EncryptContext
) : AbstractEncryptor(context) {

    init {
        val privateKey = context.privateKey
        val publicKey = context.publicKey
        require(!StringUtils.isAnyEmpty(privateKey, publicKey)) {
            "RSA公私钥均需要提供，公钥加密，私钥解密。"
        }
    }

    /**
     * 获得当前算法
     */
    override fun algorithm() = AlgorithmType.RSA

    /**
     * 加密
     *
     * @param value      待加密字符串
     * @param encodeType 加密后的编码格式
     */
    override fun encrypt(value: String?, encodeType: EncodeType?): String =
        if (encodeType == EncodeType.HEX) {
            encryptByRsaHex(value, context.publicKey)
        } else {
            encryptByRsa(value, context.publicKey)
        }

    /**
     * 解密
     *
     * @param value      待加密字符串
     */
    override fun decrypt(value: String?): String =
        decryptByRsa(value, context.privateKey)

}
